package com.masiyi.gitee.template;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.masiyi.gitee.config.GiteeProperties;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author masiyi
 */
@Slf4j
public class GiteeTemplate {


    private GiteeProperties giteeProperties;

    public GiteeTemplate(GiteeProperties giteeProperties) {
        this.giteeProperties = giteeProperties;
    }

    /**
     * 上传文件
     */
    public String putObject(InputStream inputStream, String message, String fileName) {
        //InputStream 转Base64
        String base64 = Base64.encode(inputStream);

        String url = giteeProperties.getHost() + "/v5/repos/" + giteeProperties.getOwner() + "/"
                + giteeProperties.getRepo() + "/contents/" + fileName;

        Map<String, String> map = new HashMap<>();
        map.put("access_token", giteeProperties.getAuthorization());
        map.put("content", base64);
        map.put("message", message);

        String jsonStringMap = new JSONObject(map).toJSONString();
        AtomicReference<String> preview = new AtomicReference<>();
        String response = HttpUtil.post(url, jsonStringMap);

        if (giteeProperties.isLog()) {
            log.error("response:{}", response);
        }

        Optional.ofNullable(JSONObject.parseObject(response))
                .map(jsonObject -> jsonObject.getJSONObject("content"))
                .map(jsonObject -> jsonObject.getString("download_url"))
                .ifPresent(preview::set);
        return preview.get();

    }


}
